import React, { Component } from 'react';
import { message, Table, Modal, Button, Icon, Form, Row, Col, Input } from 'antd';
import Edit from './edit.js';
import './index.less';

import * as shopApi from 'common/api/ShopApi.js';

const FormItem = Form.Item;
const confirm = Modal.confirm;
const ButtonGroup = Button.Group;

message.config({
  top: 50,
  duration: 1,
  maxCount: 1,
});

/**
 * 系统用户管理
 * @param {dataSource} 	列表数据
 * @param {pagination} 	列表分页信息
 * @param {loading} 		列表加载中	
 * @param {selectKeys} 	选中行
 * @param {editVisible} 编辑弹框显示状态
 * @param {editId} 			编辑信息ID
 * @param {editTitle} 	编辑框标题
 * 
 * @param {primaryKey}	主键ID
 * @param {filter}			筛选字段
 * @param	{initFiter}		初始化筛选字段
 * @param	{filterField}	查询条件框
 */
class Index extends Component{
	
	constructor(props) {
    super(props);
    this.state = {
    	dataSource: [],
			pagination: { current: 1, pageSize: 10, size: "default", showTotal: (total, range) => {return `当前 ${range[0]}-${range[1]}, 共  ${total} 条`} },
			loading: false,
			selectKeys: [],
			editVisible: false,
			editId: "",
			editTitle: "",
			
			//需要设置以下内容
			primaryKey: "goodsId",
			filter: {
				goodsName: "",
			},
			initFiter: {
				goodsName: "",
			},
			filterField: [
				{
					name: "商品名称",
					code: "goodsName",
				}
			]
    },
    this.columns = [
    	{ title: '商品名称', dataIndex: 'goodsName', key: 'goodsName', width: 200 }, 
    	{ title: '商品标题', dataIndex: 'goodsTitle', key: 'goodsTitle'}, 
    	{ title: '商品价格', dataIndex: 'goodsPriceStr', key: 'goodsPriceStr', width: 90 }, 
    	{ title: '商品库存', dataIndex: 'goodsStock', key: 'goodsStock', width: 90 }, 
		  { title: '操作', dataIndex: 'action', key: 'action', width: 100, align: 'center',
			  render: (text, record, index) => {
			  	return(
			  		<div key={index} className="list_tool_icon">
				      <Icon type="edit" onClick={() => this.editPage(record)}/>
				      <Icon type="delete" onClick={() => this.deleteRow(record)}/>
			  		</div>
			  	)
			  }
			}
		];
	}
	
	//删除方法
	delete = (ids) => {
		confirm({
	    title: '确定删除当前商品?',
	    content: '',
	    okText: '确定',
	    okType: 'danger',
	    cancelText: '取消',
	    onOk: () => {
	      shopApi.shopGoodsDel({
	      	id: ids
	      }).then(result => {
	      	if(result && result.code == 20000){
	      		this.refresh();
	      		message.success('操作成功');
	      	}
	      })
	    },
	    onCancel: () => {
	      console.log('Cancel');
	    },
	  });
	}
	
	//请求数据
	fetch = () => {
    const { pagination, filter } = this.state;
    this.setState({ loading: true });
    shopApi.shopGoodsList({
    	page: pagination.current,
    	limit: pagination.pageSize,
    	goodsName: filter.goodsName,
    }).then(result => {
    	if(result.code == 20000){
    		pagination.total = result.count;
    		this.setState({
	        loading: false,
	        dataSource: result.data,
	        pagination,
	      });
    	}
    })
  }
	
	
	//新建页面
	addPage = () => {
		this.setState({
      editVisible: true,
      editId: "",
      editTitle: "新建"
    });
	}
	
	//编辑页面
	editPage = (record) => {
		this.setState({
      editVisible: true,
      editId: record[this.state.primaryKey],
      editTitle: "编辑"
    });
	}
	
	//关闭编辑页面
	editClose = (isRefresh) => {
		this.setState({
      editVisible: false,
    });
    if(isRefresh){
    	this.refresh();
    	message.success('操作成功');
    }
	}
	
	//删除单个
	deleteRow = (record) => {
	 	this.delete(record[this.state.primaryKey]);
	} 
	
	//删除选中
	deleteSelect = () => {
		const { selectKeys } = this.state;
		if(selectKeys.length > 0){
			this.delete(selectKeys.join(","))
		}else{
			message.error('请选择要删除的行');
		}
	}
	
	//刷新事件
	refresh = () => {
		this.setState({ 
			loading: true,
			pagination: { current: 1, pageSize: 10 },
		}, function(){
			this.fetch();
		});
	}
	
	//搜索事件
	handleSearch = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
    	this.setState({
    		filter: values
    	}, function(){
    		this.refresh();
    	})
    });
  }
	
	//选中事件
	selectChange = (selectedRowKeys, selectedRows) => {
		var arr = [];
		selectedRows.map((item, index) => {
			arr.push(item[this.state.primaryKey]);
		})
		this.setState({
			selectKeys: arr
		})
	}
	
	//分页事件
	handleTableChange = (pagination, filters, sorter) => {
		const pager = { ...this.state.pagination };
    pager.current = pagination.current;
    this.setState({
      pagination: pager,
    }, function(){
    	this.fetch();
    });
	}
	
	handleReset = () => {
   	this.props.form.setFieldsValue(this.state.initFiter);
   	this.setState({
			filter: this.state.initFiter
		}, function(){
			this.refresh();
		})
  }
	
 	componentDidMount() {
    this.props.form.setFieldsValue(this.state.initFiter);
   	this.setState({
			filter: this.state.initFiter
		}, function(){
			this.refresh();
		})
  }
 	
	render(){
		const { dataSource, pagination, loading, editVisible, editId, editTitle, filterField } = this.state;
		const { getFieldDecorator } = this.props.form;
		return(
			<div className="sysUser">
			
				{/*查询条件*/}
				<Form
	        className="ant-advanced-search-form"
	        onSubmit={this.handleSearch}>
				 	<Row gutter={24}>
				 		{
				 			filterField.map((item, index) => {
				 				return(
				 					<Col key={index} span={6}>
					          <FormItem label={item.name}>
					            {getFieldDecorator(item.code)(
					              <Input placeholder="" autoComplete="off"/>
					            )}
					          </FormItem>
					        </Col>
				 				)
				 			})
				 		}
		        <Col span={6} className="search">
	            <Button type="primary" htmlType="submit"><Icon type="search" /></Button>
             	<Button style={{ marginLeft: 8 }} onClick={this.handleReset}>重置</Button>
	          </Col>
				 	</Row>
				</Form>
				
				{/*操作工具*/}
				<ButtonGroup style={{marginBottom: '20px'}}>
				 	<Button type="primary" onClick={this.deleteSelect.bind(this)}>
		        <Icon type="delete" />删除
		      </Button>
		      <Button type="primary" onClick={this.addPage.bind(this)}>
		      	<Icon type="plus" />新建
		      </Button>
		    </ButtonGroup>
		    
		    {/*表格数据*/}
				<Table 
					rowSelection={{ onChange: (selectedRowKeys, selectedRows) => this.selectChange(selectedRowKeys, selectedRows) }}
					columns={this.columns}
					dataSource={dataSource}
					pagination={pagination}
        	loading={loading}
        	onChange={this.handleTableChange}
					size="default"
					bordered={true}>
				</Table>
				
				{/*编辑页面*/}
				<Edit 
					id={editId} 
					editTitle={editTitle} 
					editVisible={editVisible}
					editClose={this.editClose.bind(this)}>
				</Edit>
			</div>
		)
	}
}

export default Form.create()(Index);